<?php
namespace backend\modules\business\controllers;

use backend\controllers\BaseController;
use common\models\BusSupplier;
use common\models\BusRepertory;
use common\models\BusTempRepertory;
use common\models\BusMemberConsume;
use yii\base\Object;
use yii\helpers\Url;
use common\models\BusConfig;
use yii\data\Pagination;
use common\extended\PHPExcel\PHPExcel;
use common\extended\system\Util;
use yii\gii\CodeFile;
/**
 * 库存(商品)管理
 * @author     chenxiaolin
 * @date        2016年2月23日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class RepertoryController extends BaseController{
    public function init(){
        parent::init();
        $this->layout = '/alert';
    }
    public function actionIndex(){
        $this->redirect(Url::toRoute("repertory/repertorymanage"));
    }
    /**
     * 库存管理
     * @date: 2016年2月25日 
     * @author: chenxiaolin
     */
    public function actionRepertorymanage(){
        $this->layout = '/agent';
        //测试接口
        /* $userInfo = $this->userInfo;
        $obj = new BusRepertory();
        $rs = $obj->updateRepertorycount(2, 10, $userInfo->shop_id, $userInfo->boss_uid, $userInfo->uid); */
        /* $data=[
            //'shopId' => $userInfo->shop_id,
            //'bossId' => $userInfo->boss_uid,
            //'uid' => $userInfo->uid,
            'repertory_name' => '保湿补水面膜',
            //'repertory_count' => 10,
            'goods_sell_price' => 100
        ];
        $rs = $obj->editRepertory(8,$data); */
        /* var_dump($rs);
        exit; */
        //获取筛选数据
        $supplier_name = $this->request->get('supplier_name','');
        $repertory_brand = $this->request->get('repertory_brand','');
        $repertory_name = $this->request->get('repertory_name','');
        $order = intval($this->request->get('order',-10000));
        $is_familly = intval($this->request->get('is_familly',-10000));
        
        //筛选条件
        $where = $this->where;
        if($supplier_name != ''){
            $where[] = "supplier_name like '%".$supplier_name."%'";
        }
        if($repertory_brand != ''){
            $where[] = "repertory_brand like '%".$repertory_brand."%'";
        }
        if($repertory_name != ''){
            $where[] = "repertory_name like '%".$repertory_name."%'";
        }
        if($order != -10000){
            $orderBy = 'repertory_count';
        }else{
            $orderBy = 'repertory_id';
        }
        if($is_familly != -10000){
            $where[] = "is_sell = 1";
        }
        $whereStr = implode ( ' and ', $where );
        $query = BusRepertory::find()->where($whereStr)->orderBy($orderBy);
        
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => $this->pageNavLimit]);
        $data = $query->offset($pages->offset)->limit($pages->limit)->all();
        //系统配置中读取数据
        //1、规格
        $specs = $this->getConfigData('规格');
        //2、品牌
        $brand = $this->getConfigData('品牌');
        //3、系列
        $series = $this->getConfigData('系列');
        //4、类别
        $category = $this->getConfigData('类别');
        //5、供应商
        $supplier = $this->getConfigData('供应商');
        return $this->render('repertorymanage',[
            'data' => $data,
            'supplier_name' => $supplier_name,
            'repertory_brand' => $repertory_brand,
            'repertory_name' => $repertory_name,
            'order' => $order,
            'is_familly' => $is_familly,
            'page' => $pages,
            'specs' =>$specs,
            'brand' => $brand,
            'series' => $series,
            'category' => $category,
            'supplier' => $supplier
        ]);
    }
    /**
     * 库存(商品)列表
     * @date: 2016年2月23日 
     * @author: chenxiaolin
     */
    public function actionList(){
        //去掉调试栏
        $this->disableDebugtool();
        //获取筛选数据
        $supplier = $this->request->get('supplier','');
        $bar_code = $this->request->get('bar_code','');
        $repertory_name = $this->request->get('repertory_name','');
        $type = $this->request->get('type',0);
        //筛选条件
        $where = $this->where;
        if($supplier != ''){
            $where[] = "supplier_name like '%".$supplier."%'";
        }
        if($bar_code != ''){
            $where[] = "bar_code like '%".$bar_code."%'";
        }
        if($repertory_name != ''){
            $where[] = "repertory_name like '%".$repertory_name."%'";
        }
        $whereStr = implode ( ' and ', $where );
        $query = BusRepertory::find()->where($whereStr);
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => $this->pageNavLimit]);
        $data = $query->offset($pages->offset)->limit($pages->limit)->all();
        //获取session值
        $session = \Yii::$app->session;
        $repertory_ids = [];
        $count = count($session['repertoryId']);
        if(!empty($session['repertoryId'])){
            $repertory_ids = $session['repertoryId'];
        }
        return $this->render('list',[
            'supplier' => $supplier,
            'bar_code' => $bar_code,
            'repertory_name' => $repertory_name,
            'repertory_ids' => $repertory_ids,
            'type' => $type,
            'data' => $data,
            'count' => $count,
            'page' => $pages
        ]);
    }
    
    
    /**
     * 添加库存(商品)
     * @date: 2016年2月23日 
     * @author: chenxiaolin
     */
    public function actionAdd(){
        if(!$this->request->isPost){
            //去掉调试栏
            $this->disableDebugtool();
            //系统配置中读取数据
            //1、规格
            $specs = $this->getConfigData('规格');
            //2、品牌
            $brand = $this->getConfigData('品牌');
            //3、系列
            $series = $this->getConfigData('系列');
            //4、类别
            $category = $this->getConfigData('类别');
            //5、供应商
            $supplier = $this->getConfigData('供应商');
            return $this->render('add',[
                'specs' => $specs,
                'brand' => $brand,
                'series' => $series,
                'category' => $category,
                'supplier' => $supplier
            ]);
        }
        //获取数据
        $userInfo = $this->userInfo;
        $repertory_name = $this->request->post('repertory_name','');
        $bar_code = $this->request->post('bar_code','');
        $is_sell = intval($this->request->post('is_sell',0));
        $goods_sell_price = floatval($this->request->post('goods_sell_price',0));
        //老板添加成本价
        if($userInfo->user_type == 3){
            $goods_cost_price = floatval($this->request->post('goods_cost_price',0));
        }
        $repertory_specs = $this->request->post('repertory_specs','');
        $repertory_brand = $this->request->post('repertory_brand','');
        $repertory_series = $this->request->post('repertory_series','');
        $repertory_category = $this->request->post('repertory_category','');
        $supplier_name = $this->request->post('supplier_name','');
        //数据验证
        if(!in_array($is_sell,[0,1]) || empty($repertory_name)){
            $this->error("参数错误！");
        }
        //保存数据
        $repertory = new BusRepertory();
        $repertory->repertory_name = $repertory_name;
        $repertory->bar_code = $bar_code;
        $repertory->is_sell = $is_sell;
        $repertory->goods_sell_price = $goods_sell_price;
        //老板添加成本价
        if($userInfo->user_type == 3){
            $repertory->goods_cost_price = $goods_cost_price;
        }elseif($userInfo->user_type == 4){
            $repertory->goods_cost_price = 0;
        }
        $repertory->repertory_specs = $repertory_specs;
        $repertory->repertory_brand = $repertory_brand;
        $repertory->repertory_series = $repertory_series;
        $repertory->repertory_category = $repertory_category;
        $repertory->supplier_name = $supplier_name;
        $repertory->repertory_count = 0;
        $repertory->shop_id = $userInfo->shop_id;
        $repertory->boss_id = $userInfo->boss_uid;
        $rs = $repertory->save(false);
        if($rs){
            $id = $repertory->repertory_id;
            echo "<script>";
            echo "top.location.href='".Url::toRoute(['repertoryinc/storage','id' => $id])."'";
            echo "</script>";
        }else{
            $this->error("添加失败！");
        }
       
    }
    
    /**
     * 编辑库存(商品)
     * @date: 2016年2月23日
     * @author: chenxiaolin
     */
    public function actionEdit(){
        //获取数据
        $repertory_id = $this->request->post('repertory_id');
        $repertory_name = $this->request->post('repertory_name','');
        $repertory_specs = $this->request->post('repertory_specs','');
        $supplier_name = $this->request->post('supplier_name','');
        $repertory_brand = $this->request->post('repertory_brand','');
        $repertory_series = $this->request->post('repertory_series','');
        $repertory_category = $this->request->post('repertory_category','');
        $bar_code = $this->request->post('bar_code','');
        $is_sell = $this->request->post('is_sell');
        //老板获取零售价、成本价
        $userInfo = $this->userInfo;
        if($userInfo->user_type == 3){
            $goods_cost_price = floatval($this->request->post('goods_cost_price',0));
            $goods_sell_price = floatval($this->request->post('goods_sell_price',0));
        }
        //修改商品信息
        $where = $this->where;
        $where[] = 'repertory_id = :id';
        $bind[':id'] = $repertory_id;
        $whereStr = implode(' and ', $where);
        $repertoryOne = BusRepertory::find()->where($whereStr,$bind)->one();
        if(empty($repertoryOne)){
            $this->error('商品不存在！');
        }
        $repertoryOne->repertory_name = $repertory_name;
        $repertoryOne->repertory_specs = $repertory_specs;
        $repertoryOne->supplier_name = $supplier_name;
        $repertoryOne->repertory_brand = $repertory_brand;
        $repertoryOne->repertory_series = $repertory_series;
        $repertoryOne->repertory_category = $repertory_category;
        $repertoryOne->bar_code = $bar_code;
        $repertoryOne->is_sell = $is_sell;
        //老板修改零售价、成本价
        if($userInfo->user_type == 3){
            $repertoryOne->goods_cost_price = $goods_cost_price;
            $repertoryOne->goods_sell_price = $goods_sell_price;
        }
        $rs = $repertoryOne->save(false);
        if(!$rs){
            $this->error("修改失败！");
        }
        $this->redirect(Url::toRoute("repertory/repertorymanage"));
    }
    /**
     * 库存盘点
     * @date: 2016年2月27日 
     * @author: chenxiaolin
     */
    public function actionRepertorycheck(){
        //获取数据
        $ids = $this->request->post('id');
        $values = $this->request->post('val');
        $transAction = \Yii::$app->db->beginTransaction();
        try {
            for($i=0;$i < count($ids); $i++){
                $repertory = BusRepertory::find()->where('repertory_id = :id',[':id' => $ids[$i]])->one();
                //修改库存
                $repertory->repertory_count = $values[$i];
                $repertory->save(false);
            }
            $transAction->commit();
            $arr=[
                'state' => 1,
                'message' => '盘点成功'
            ];
            return json_encode($arr);
        } catch (\Exception $e) {
            $transAction->rollBack();
            $arr=[
                'state' => 0,
                'message' => '盘点失败'
            ];
            return json_encode($arr);
        }
        
    }
    
    /**
     * 出入库临时记录
     * @date: 2016年3月7日 
     * @author: chenxiaolin
     */
    public function actionRepertorytemp(){
        $id = $this->request->post('id',0);
        //出库\入库标志:(-1:入库,-2:出库)
        $type = $this->request->post('type',0);
        //保存\删除标志:(1:保存,2:删除,3:清空session)
        $flag = $this->request->post('flag',0);
        if(in_array($flag, [1,2])){
            if($id < 1){
                $this->error('参数错误！');
            }
        }
        if(!in_array($flag,[1,2,3]) || !in_array($type, [-1,-2])){
            $this->error('参数错误！');
        }
        $session = \Yii::$app->session;
        
        if($flag == 1){//保存临时数据到session
            if(empty($session['repertoryId'])){
                $session['repertoryId'] = [];
            }
            $arr1 = $session['repertoryId'];
            if(!in_array($id, $arr1)){
                array_push($arr1,$id);
            }
            $session['repertoryId'] = $arr1;
            $rs = [
               'state' => 1,
               'count' => count($session['repertoryId'])
            ];
            return json_encode($rs);
        }
        if($flag == 2){//删除临时数据
            $arr2 = $session['repertoryId'];
            $key = array_search($id, $arr2);
            if($key !== false){
                array_splice($arr2, $key,1);
                $session['repertoryId'] = $arr2;
                $rs = [
                    'state' => 1,
                    'count' => count($session['repertoryId'])
                ];
                return json_encode($rs);
            }
        }
        if($flag == 3){//清空session
            unset($session['repertoryId']);
            $rs = [
                'state' => 1,
                'type' => $type
            ];
            return json_encode($rs);
        }
    }
    
    /**
     * 扫码枪出入库临时记录(记录条形码)
     * @date: 2016年3月7日
     * @author: chenxiaolin
     */
    public function actionBarcodetemp(){
        //获取条形码
        $code = $this->request->post('code',0);
        if(empty($code)){
            $rs = [
                'state' => 2,
                'message' => '请输入条形码！'
            ];
            return json_encode($rs);
        }
        //查询商品是否存在
        $where = $this->where;
        $where[] = 'bar_code = :code';
        $bind[':code'] = $code;
        $whereStr = implode(' and ', $where);
        $repertory = BusRepertory::find()->where($whereStr,$bind)->asArray()->all();
        
        if(empty($repertory)){
            $rs = [
                'state' => 2,
                'message' => '商品不存在，请添加！'
            ];
            return json_encode($rs);
        }
        
        $session = \Yii::$app->session;
    
        //保存临时数据到session
        if(empty($session['repertoryId'])){
            $session['repertoryId'] = [];
        }
        $arr1 = $session['repertoryId'];
        foreach ($repertory as $k => $v){
            if(!in_array($v['repertory_id'], $arr1)){
                array_push($arr1,$v['repertory_id']);
            }
            $session['repertoryId'] = $arr1;
        }
        $rs = [
            'state' => 1,
        ];
        return json_encode($rs);
        
    }
    
    /**
     * 导出Excel
     * @date: 2016年2月27日 
     * @author: chenxiaolin
     */
    public function actionExportexcel(){
        $userInfo = $this->userInfo;
        //创建一个excel
        $objPHPExcel = new \PHPExcel();
        //创建新的内置表
        $objPHPExcel->createSheet();
        //设置活动sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //获取当前活动sheet
        $objSheet = $objPHPExcel->getActiveSheet();
        //设置title
        $objSheet->setCellValue('A1','商品名称')->setCellValue('B1','规格')
            ->setCellValue('C1','库存')->setCellValue('D1','零售价')->setCellValue('E1','供应商')
            ->setCellValue('F1','品牌')->setCellValue('G1','系列')->setCellValue('H1','类别')
            ->setCellValue('I1','条形码')->setCellValue('J1','是否家居');
        //老板
        if($userInfo->user_type == 3){
            $objSheet->setCellValue('K1','成本价');
        }
        //获取数据
        $where = $this->where;
        $whereStr = implode(' and ', $where);
        $repertory = BusRepertory::find()->where($whereStr)->asArray()->all();
        $i = 2;
        foreach ($repertory as $k => $v){
            $v['is_sell'] = $v['is_sell'] == 1 ? '是' : '否';
            $objSheet->setCellValue('A'.$i,$v['repertory_name'])->setCellValue('B'.$i,$v['repertory_specs'])
                ->setCellValue('C'.$i,$v['repertory_count'])->setCellValue('D'.$i,$v['goods_sell_price'])
                ->setCellValue('E'.$i,$v['supplier_name'])->setCellValue('F'.$i,$v['repertory_brand'])
                ->setCellValue('G'.$i,$v['repertory_series'])->setCellValue('H'.$i,$v['repertory_category'])
                ->setCellValue('I'.$i,$v['bar_code'])->setCellValue('J'.$i,$v['is_sell']);
            //老板
            if($userInfo->user_type == 3){
                $objSheet->setCellValue('K'.$i,$v['goods_cost_price']);
            }
            $i++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        Util::browser_export('Excel5','repertory.xls');//输出到浏览器
        $objWriter->save("php://output");
    }
    
    /**
     * 删除(出入库)选中数据
     * @date: 2016年3月10日 
     * @author: chenxiaolin
     */
    public function actionDelselect(){
        $id = $this->request->get('id',0);
        //出入库标志
        $type = $this->request->get('type',0);
        $session = \Yii::$app->session;
        if($id < 1 || !in_array($type, [1,2])){
            $this->error('参数错误！');
        }
        $where = $this->where;
        $where[] = 'repertory_id = :id';
        $bind[':id'] = $id;
        $whereStr = implode(' and ', $where);
        $repertory = BusRepertory::find()->where($whereStr,$bind)->one();
        if(empty($repertory)){
            $this->error('参数错误！');
        }
        //根据id清除临时数据
        if(!empty($session['repertoryId'])){
            $arr1 = $session['repertoryId'];
            $key1 = array_search($id, $arr1);
            if($key1 !== false){
                array_splice($arr1, $key1,1);
                $session['repertoryId'] = $arr1;
            }
        }
        if(!empty($session['repertoryNum'])){
            $num = $session['repertoryNum'];
            foreach( $num as $key => $value ) {
                if(in_array($id,$value)){
                    unset($num[$key]);
                    $session['repertoryNum'] = $num;
                } 
            }
        }
        if($type == 1){//入库
            $this->redirect(Url::toRoute(['repertoryinc/storage']));
        }
        if($type == 2){//出库
            $this->redirect(Url::toRoute(['goodsdec/repertoryout']));
        }
    }
    
    /**
     * 记录临时入库数量
     * @date: 2016年3月24日
     * @author: chenxiaolin
     */
    public function actionTempnum(){
        $id = $this->request->post('id',0);
        $num = intval($this->request->post('num',0));
        if($id < 1 || $num < 0){
            $rs = [
                'state' => 0,
                'message' => '参数错误！'
            ];
        }
        $session = \Yii::$app->session;
        if(empty($session['repertoryNum'])){
            $session['repertoryNum'] = [[
                'id' => $id,
                'num' => $num
            ]];
        }
        $arr1 = $session['repertoryNum'];
        $arr = [
            'id' => $id,
            'num' => $num
        ];
        $idArr = [];
        foreach ($arr1 as $k1 => $v1){
            $idArr[$k1] = $v1['id'];
        }
        if(!in_array($id, $idArr)){
            array_push($arr1,$arr);
        }else{
            foreach ($arr1 as $k => $v){
                if($v['id'] == $id){
                    $arr1[$k]['num'] = $num;
                }
            }
        }
        $session['repertoryNum'] = $arr1;
    }
    
    /**
     * 获取配置表中数据
     * @date: 2016年2月23日 
     * @author: chenxiaolin
     */
    private function getConfigData($key){
        $where = $this->where;
        $where[] = 'config_type = 6';
        $where[] = 'config_key = :key';
        $bind[':key'] = $key;
        $whereStr = implode(" and ", $where);
        $data = BusConfig::find()->where($whereStr,$bind)->all();
        return $data;
    }
}